package com.woniuxy.company5.controller;

import com.woniuxy.company5.util.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author ：fengsir
 * @date ：Created in 2022/12/8 10:35
 * @description：
 * @modified By：
 * @version: $
 */
@RestController
public class BaseController {
    @RequestMapping("upload")
    public Result upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {

        //获取文件在服务器的储存位置
        String path = request.getServletContext().getRealPath("/upload");
        File filePath = new File(path);
        if (!filePath.exists() && !filePath.isDirectory()) {
            filePath.mkdir();
        }

        //获取原始文件名称(包含格式)
        String originalFileName = file.getOriginalFilename();

        //获取文件类型，以最后一个`.`为标识
        String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);

        //获取文件名称（不包含格式）
        String name = originalFileName.substring(0, originalFileName.lastIndexOf("."));

        //设置文件新名称: 当前时间+文件名称（不包含格式）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf.format(new Date());
        String fileName = date + name + "." + type;

        //在指定路径下创建一个文件
        File targetFile = new File(path, fileName);
        //将文件保存到服务器指定位置
        try {
            file.transferTo(targetFile);
            return Result.ok("http://localhost:9000/upload/" + fileName);
            //将文件在服务器的存储路径返回

        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("上传失败");
        }
    }
    /**
     * todo 下载文件
     *
     * @param response
     * @param
     */
    @GetMapping("downLoadFile")
    public void downLoadFile(HttpServletResponse response, @RequestParam("filename") String filename, HttpServletRequest request) {
        response.setHeader("Content-Type", "application/octet-stream");
        //下载文件路径
        String path = request.getServletContext().getRealPath("/upload");
        OutputStream out = null;
        try {
            //通过文件路径获得File对象(假如此路径中有一个download.pdf文件)
            File file = new File(path + File.separator + filename);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            FileInputStream fin = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fin.read(data);
            fin.close();
            out = response.getOutputStream();
            out.write(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
